<?php
/**
 * @class-name   :  DailyEmailListModel.class.php
 * @description  :  Model Action For Daily Email List.
 * @author       :  Stephen.Mo<stephen.mo@achievo.com>
 * @date         :  2010-06-10
 */

class DailyEmailListModel  extends model {

    static public function getTableName() {
        return 'send_email_list';
    }
    
    static public function getInstance() {
        static $instance = null ;
        return $instance ? ($instance) : ($instance = new DailyEmailListModel()) ;
    }

    private function countRecords() {
        $query = "SELECT count(*) AS Total FROM ".$this->getTableName()." WHERE 1 ";
        $data = Model::selectBySql($query);
        return (isset($data[0]['Total'])) ? $data[0]['Total'] : 0;
    }

    private function checkIsExists($name,$email) {
        $query = "SELECT id FROM ".$this->getTableName()." WHERE name='".$name."' AND email='".$email."' LIMIT 1";
        $data = Model::selectBySql($query);
        return (isset($data[0]['id']) && $data[0]['id']>0) ? true : false;
    }

    public function getEmailList($page,$sidx,$rows=5,$sord) {
        $page = (!empty($page)) ? $page : 1;
        $rows = (!empty($rows)) ? $rows : 5;
        //get all records.
        $total = $this->countRecords();
        $limit_str = ' LIMIT '.($page-1)*$rows.",".$rows;
        
        $query = "SELECT id,name,email FROM ".$this->getTableName().
                 " WHERE 1 ".
                 " ORDER BY ".$sidx." ".$sord.$limit_str;
        $data = Model::selectBySql($query);
        $result = array();
        foreach($data as $key=>$value) {
            $result[] = array('id'=>$value['id'],'cell'=>array($value['id'],$value['name'],$value['email']));
        }
        return array('total'=>$total,'data'=>$result);
    }

    public function addEmailList ($name,$email) {
        if ($this->checkIsExists($name,$email)) return true;
        $query = "INSERT INTO ".$this->getTableName()." (id,name,email) VALUES (0,'".$name."','".$email."') ";
        $data = Model::updateBySql($query);
        return $data;
    }

    public function editEmailList($id,$name,$email) {
        if ($this->checkIsExists($name,$email)) return true;
        $query = "UPDATE ".$this->getTableName()." SET name='".$name."',email='".$email."' WHERE id=".$id;
        $data = Model::updateBySql($query);
        return $data;
    }
    
    public function delEmailList($id) {
        $query = "DELETE FROM ".$this->getTableName()." WHERE id=".$id;
        $data = Model::updateBySql($query);
        return $data;
    }


}


?>